local common = require "common"
local utils = require "utils"

local M = {}

local map_length = 20
local map_width = 20

M.map = {}
M.player2pos = {}

function M.new_map_obj(player_id, type, x, y)
    local map_obj = {
        id = player_id,
        type = type,
        x = x,
        y = y,
    }

    return map_obj
end

function M.init()
    for i = 0, map_width do
        local t = {}
        for j = 0, map_length do
            t[j] = {}
        end

        M.map[i] = t
    end
end

function M.add_player_obj(player_id, x, y)
    local old_obj = M.player2pos[player_id]
    if not old_obj then
        local map_obj = M.new_map_obj(player_id, common.OBJ_TYPE.PLAYER, x, y)
        M.player2pos[player_id] = map_obj

        M.map[y][x][player_id] = map_obj

        print("map add_player_obj new:", player_id, y, x)
    else
        local old_x = old_obj.x
        local old_y = old_obj.y
        M.map[old_y][old_x][player_id] = nil

        old_obj.x = x
        old_obj.y = y
        M.map[y][x][player_id] = old_obj
        print("map update_player_obj:", player_id, old_y, old_x, y, x)
    end
end

function M.update_player_obj(player_id, x, y)
    M.add_player_obj(player_id, x, y)
end

function M.remove_player_obj(player_id)
    local obj = M.player2pos[player_id]
    if obj then
        M.player2pos[player_id] = nil
        M.map[obj.y][obj.x][player_id] = nil
        print("map remove_player_obj:", player_id)
    end
end

function M.test_print_map()
    local out = ""
    for i = 0, map_width do
        for j = 0, map_length do
            local count = utils.get_table_size(M.map[i][j])
            if count > 0 then
                out = out .. "\27[1;32;43m" .. tostring(count) .. "\27[0m" .. " "
            else
                out = out .. tostring(count) .. " "
            end
            
        end
        out = out .. '\n'
    end
    print(out)
end

return M